package com.eazy.lkv2.core.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import com.eazy.lkv2.core.web.utils.DateUtils;
import com.eazy.lkv2.core.web.utils.IPUtil;
import com.eazy.lkv2.web.entity.Log;
import com.eazy.lkv2.web.service.system.SystemLogService;

import eu.bitwalker.useragentutils.UserAgent;

/**
 * 系統訪問日誌記錄
 * @author jzx
 * 2016-07-14 16:04:00 星期四
 */
public class SystemLogInterceptor extends BaseInterceptor {

	@Autowired
	private SystemLogService systemLogService;
	
	private Long beginTime;// 1、开始时间
	private Long endTime;// 2、结束时间
	
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		beginTime = System.currentTimeMillis();//计时
		return true;
	}

	public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent")); 
		String os=userAgent.getOperatingSystem().getName();	//获取客户端操作系统
		String browser=userAgent.getBrowser().getName();	//获取客户端浏览器
		
		Log log=new Log();
		log.setOs(os);
		log.setBrowser(browser);
		log.setIp(IPUtil.getIpAddress(request));
		log.setCreateDate(DateUtils.getSysTimestamp());
		
		// 过滤本地IP
		if(!IPUtil.getIpAddress(request).equals("127.0.0.1"))
			systemLogService.create(log);
	}
}
